<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :show-close="false"
    :visible.sync="visible">
    <el-form  :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="140px">
      <el-form-item label="名称：" prop="name">
        <el-input clearable v-model="dataForm.name" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="请求地址：" prop="url">
        <el-input clearable v-model="dataForm.url" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="请求类型：" prop="method">
        <el-tag
          style="margin-right:10px;cursor: pointer;"
          v-for="(tag,index) in methodsList"
          @click="selecttag(tag,index)"
          :key="index"
          :type="tag.type">
          {{tag.name}}
        </el-tag>
      </el-form-item>
      <el-form-item v-if="dataForm.method=='POST'" label="POST请求参数：" prop="bodyData">
        <el-input clearable @focus="editJson('bodyData',dataForm.bodyData)"  type="textarea" autosize v-model="dataForm.bodyData" placeholder=""></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.method!='POST'&&dataForm.method!='0'" label="其他请求参数：" prop="parameter">
        <el-input clearable  type="textarea" autosize v-model="dataForm.parameter" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="参数类型：" prop="contentType">
          <el-select clearable v-model="dataForm.contentType" placeholder="请选择">
            <el-option
              v-for="(item,i) in options"
              :key="i"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="token参数位置：" prop="keyPath">
        <el-input clearable v-model="dataForm.keyPath" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="参数是否加密：" prop="status">
        <el-radio v-model="dataForm.status" label="1">加密</el-radio>
        <el-radio v-model="dataForm.status" label="2">不加密</el-radio>
      </el-form-item>
      <el-form-item label="是否使用内置参数：" prop="inlay">
        <el-radio v-model="dataForm.inlay" label="1">是</el-radio>
        <el-radio v-model="dataForm.inlay" label="2">否</el-radio>
      </el-form-item>
      <el-form-item label="内置参数：" prop="inlayParameter">
        <el-input clearable :disabled="dataForm.inlay=='2'||dataForm.inlay==''" v-model="dataForm.inlayParameter" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="headr请求参数：" prop="heardData">
        <el-input clearable @focus="editJson('headr',dataForm.heardData)"  type="textarea" autosize v-model="dataForm.heardData" placeholder=""></el-input>
      </el-form-item>
    </el-form>
    <div style="padding-left:60px;color:#17B3A3;word-wrap: break-word;word-break: normal;" v-if="veriicationStr!=''"><span>验证成功：</span>{{veriicationStr}}</div>
    <span  slot="footer" class="dialog-footer">
      <el-button @click="verification">在线验证</el-button>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>



    <el-dialog
      width="30%"
      title="JSON参数编辑"
      :visible.sync="editPostJsonFlag"
      :close-on-click-modal="false"
      append-to-body>
      <div v-if="editPostJsonFlag">
        <vue-json-editor
          v-model="resultInfo"
          :showBtns="false"
          :mode="'code'"
          @json-change="onJsonChange"
          @json-save="onJsonSave"
          @has-error="onError"
        />
        <br>
      <el-button type="primary" @click="checkJson">确定</el-button>
    </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'
  import vueJsonEditor from 'vue-json-editor'
  import request from '@/utils/request'
  import { getToken, setToken, removeToken } from '@/utils/auth'
  export default {
    components:{
      vueJsonEditor
    },
    data () {
      var validatePass = (rule, value, callback) => {
        if (value === '0') {
          callback(new Error('请选择请求类型'));
        } else {
          if (this.dataForm.method !== 'POST') {
            this.$refs.dataForm.validateField('checkPass');
          }
          callback();
        }
      };
      return {
        conmitFormData:null,
        jsonType:'',
        veriicationStr:"",
        hasJsonFlag:true,  // json是否验证通过
        // json数据
        resultInfo: {},

        methodsList: [],
        options: [],
        editPostJsonFlag: false,
        // -------------
        visible: false,
        menuList: [],
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataForm: {
          name: '',
          url: '',
          method: '0',
          contentType: '',
          keyPath: '',
          body: '',
          parameter: '',
          status:'',
          inlay:'',
          inlayParameter:'',
          heardData:'',
          bodyData:''
        },
        dataRule: {
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
          url: [{ required: false, message: '地址不能为空', trigger: 'blur' }],
          method: [{required: false,  validator: validatePass , trigger: 'blur' }],
          contentType: [{ required: false, message: '参数类型不能为空', trigger: 'change' }],
          keyPath: [{ required: false, message: 'token值所处路径不能为空', trigger: 'blur' }]
        }
      }
    },
    methods: {
      closeDialog(){
        this.veriicationStr=''
        this.dataForm = {
          name: '',
          url: '',
          method: '0',
          contentType: '',
          keyPath: '',
          body: '',
          parameter: '',
          status:'',
          inlay:'',
          heardData:'',
          inlayParameter:'',
          bodyData:''
        }
        this.resultInfo = {}
        this.visible = false
        this.$refs['dataForm'].resetFields()
      },
      verification(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let params = JSON.parse(JSON.stringify(this.dataForm))
            params.body = "" 
            params.bodyData = params.bodyData?JSON.parse(params.bodyData):null
            params.heardData = params.heardData?JSON.parse(params.heardData):null
            this.conmitFormData = JSON.parse(JSON.stringify(params))
            request({
              url: `/ht-datadevelop/token/manage/getApiTokenCheck`,
              method: 'post',
              data: this.conmitFormData
            }).then((res) => {
              if (res.code === 200) {
                this.veriicationStr = res.token
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      },
      onJsonChange (value) {
        // 实时保存
        this.onJsonSave(value)
      },
      onJsonSave (value) {
        this.resultInfo = value
        this.hasJsonFlag = true
      },
      onError(value) {
        this.hasJsonFlag = false
      },
      // 检查json
      checkJson(){
        if(this.jsonType=='headr'){
          this.dataForm.heardData = JSON.stringify(this.resultInfo)
        }else{
          this.dataForm.bodyData = JSON.stringify(this.resultInfo)
        }
        this.editPostJsonFlag = false
        return true
      },
      editJson (v,jsonObj) {
        if(jsonObj){  
          this.resultInfo = JSON.parse(jsonObj) //json编辑器数据
        }else{
          this.resultInfo = {}
        }
        
        this.jsonType = v
        this.editPostJsonFlag = true
      },
      selecttag (tag, i) {
        this.methodsList.forEach((item,index)=> {
          item.type = ""
        })
        this.methodsList[i].type = "warning"
        this.dataForm['method'] = tag.name
      },
      editData(v){
        this.visible = true 
     
        this.dataForm = JSON.parse(JSON.stringify(v)) //复制编辑对象数据

        this.dataForm.bodyData = v.bodyData?JSON.stringify(v.bodyData):'' //用来显示的字符串数据
        this.dataForm.heardData =v.heardData?JSON.stringify(v.heardData):'' //用来显示的字符串数据

        this.methodsList.forEach((item,index)=> {
          if(item.name==v.method){
            item.type = "warning"
          }
        })
      },
      init (row) {
        request({
          url: '/ht-datadevelop/sys/common/getContentTypeList',
          method: 'get',
          params:{}
        }).then((res) => {
           this.visible = true
           this.options = res.data
        })
        request({
          url: '/ht-datadevelop/sys/common/getRequestMethodList',
          method: 'get',
          params:{token:getToken()}
        }).then((res) => {
          this.methodsList  = []
          res.data.forEach((item,index)=>{
            this.methodsList.push({
              name:item,
              type:''
            })
          })
          if(row){
            this.editData(row)
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        let p = JSON.parse(JSON.stringify(this.dataForm))
        if(p.bodyData==''){
          p.bodyData = null
        }else{
          p.bodyData = JSON.parse(p.bodyData)
        }

        if(p.heardData==''){
          p.heardData = null
        }else{
          p.heardData = JSON.parse(p.heardData)
        }
        console.log(p)

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            request({
              url: `/ht-datadevelop/token/manage/saveOrUpdateTokenConfig`,
              method: 'post',
              data: p
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.closeDialog()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>


<style lang="scss" scoped>
  >>>.el-select{
    display: block !important;
  }
  .el-form{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  .el-form-item{
    width: 50%;
  }
 ul{
  margin-left: 0 !important;
  padding-left: 0 !important;
  .lis{
    margin-bottom: 6px;
    list-style: none;
    display: flex;
    span:nth-child(1){
      width: 45%;
    }
    span:nth-child(2){
      width: 45%;
    }
    span:nth-child(3){
      width: 10%;
      text-align: center;
      padding-top: 6px;
      cursor: pointer;
      color: red;
    }
    span{
      display: block;
      >>>.el-input{
        display: inline-block;
        width:80%;
      }
    }
  }
 }
</style>